package com.landeb.shop.huo.act;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.adapter.ActAddressSelectLVAdapter;
import com.landeb.shop.huo.bean.BeanActAddressSelect;
import com.landeb.shop.huo.bean.BeanStatusInfo;
import com.landeb.shop.huo.httpRequest.ActAddressSelectRequest;
import com.landeb.shop.huo.httpRequest.ActHistoryRequest;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class AddressSelectActivity extends BaseActivity implements View.OnClickListener {

    private SwipeRefreshLayout mSRL;

    private LinearLayout btnBack;
    private Button btnAddAddress;

    private ListView mListView;
    private List<BeanActAddressSelect.DataBean> mList;
    private ActAddressSelectLVAdapter mAdapter;

    private OkHttpClient client;
    private Retrofit mRetrofit;
    private String mUrl;
    private ActAddressSelectRequest mRequest;
    private boolean isRefreshing = false;

    private int fromFlag;


    public static void toAct(Context context) {
        Intent intent = new Intent(context, AddressSelectActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_select);


        Intent intent = getIntent();
        fromFlag = intent.getIntExtra("flag", 0);

        client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(ActAddressSelectRequest.class);

        initView();
        initData();
        initEvent();

        refresh();
    }

    private void refresh() {

        if (!isRefreshing) {

            isRefreshing = true;
            mSRL.setRefreshing(true);

            mRequest.getAddressList()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanActAddressSelect>() {
                        @Override
                        public void onCompleted() {
                            Log.e("getAddressList", "onCompleted: ");
                            mSRL.setRefreshing(false);
                            isRefreshing = false;
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.e("getAddressList", "onError: " + e.toString());
                            mSRL.setRefreshing(false);
                            isRefreshing = false;

                        }

                        @Override
                        public void onNext(BeanActAddressSelect beanActAddressSelect) {

                            if (beanActAddressSelect.getStatus() == 1) {

                                mList.clear();
                                mList.addAll(beanActAddressSelect.getData());
                                mAdapter.notifyDataSetChanged();

                            } else {

                                Toast.makeText(AddressSelectActivity.this, beanActAddressSelect.getInfo(), Toast.LENGTH_SHORT).show();
                            }

                        }
                    });

        }
    }

    private void initEvent() {

        mSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        btnBack.setOnClickListener(this);
        btnAddAddress.setOnClickListener(this);

        mAdapter = new ActAddressSelectLVAdapter(AddressSelectActivity.this, mList);

        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO: 2016/11/29 lv点击事件

                //如果是订单页创建 才finish()
                if (fromFlag == CreateOrderActivity.FLAG_COACT) {

                    String ID = mList.get(position).getId();
                    String name = mList.get(position).getRealname();
                    String phoneNum = mList.get(position).getMobile();
                    String address = mList.get(position).getProvince() + mList.get(position).getCity()
                            + mList.get(position).getCountry() + mList.get(position).getTown() + mList.get(position).getAddress();

                    Intent intent = new Intent();
                    intent.putExtra("id", ID);
                    intent.putExtra("name", name);
                    intent.putExtra("phoneNum", phoneNum);
                    intent.putExtra("address", address);

                    Log.e( "onItemClick: ",ID+"----"+name+"----"+phoneNum+"----"+address );

                    setResult(RESULT_OK, intent);
                    finish();
                }

//                Toast.makeText(AddressSelectActivity.this, ID, Toast.LENGTH_SHORT).show();

            }
        });

        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                                                 @Override
                                                 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                                                     // TODO: 2016/11/29 长按删除
                                                     final String ID = mList.get(position).getId();

//                Toast.makeText(AddressSelectActivity.this, ID + "L", Toast.LENGTH_SHORT).show();
                                                     AlertDialog.Builder builder = new AlertDialog.Builder(AddressSelectActivity.this);
                                                     builder.setTitle("系统提示")
                                                             .setCancelable(false)
                                                             .setPositiveButton("取消", null)
                                                             .setNegativeButton("设为默认", new DialogInterface.OnClickListener() {
                                                                         @Override
                                                                         public void onClick(DialogInterface dialog, int which) {

                                                                             mRequest.setDefault(ID)
                                                                                     .subscribeOn(Schedulers.io())
                                                                                     .observeOn(AndroidSchedulers.mainThread())
                                                                                     .subscribe(new Subscriber<BeanStatusInfo>() {
                                                                                                    @Override
                                                                                                    public void onCompleted() {
                                                                                                        Log.e("setDefault", "onCompleted: ");
                                                                                                    }

                                                                                                    @Override
                                                                                                    public void onError(Throwable e) {
                                                                                                        Log.e("setDefault", "onError: " + e.toString());

                                                                                                    }

                                                                                                    @Override
                                                                                                    public void onNext(BeanStatusInfo beanStatusInfo) {

                                                                                                        if (beanStatusInfo.getStatus() == 1) {

                                                                                                            refresh();

                                                                                                        } else {
                                                                                                            Toast.makeText(AddressSelectActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();

                                                                                                        }

                                                                                                    }
                                                                                                }

                                                                                     );

                                                                         }
                                                                     }

                                                             )
                                                             .

                                                                     setNeutralButton("删除", new DialogInterface.OnClickListener() {
                                                                                 @Override
                                                                                 public void onClick(DialogInterface dialog, int which) {

                                                                                     mRequest.removeAddress(ID)
                                                                                             .subscribeOn(Schedulers.io())
                                                                                             .observeOn(AndroidSchedulers.mainThread())
                                                                                             .subscribe(new Subscriber<BeanStatusInfo>() {
                                                                                                            @Override
                                                                                                            public void onCompleted() {
                                                                                                                Log.e("removeAddress", "onCompleted: ");
                                                                                                            }

                                                                                                            @Override
                                                                                                            public void onError(Throwable e) {
                                                                                                                Log.e("removeAddress", "onError: " + e.toString());

                                                                                                            }

                                                                                                            @Override
                                                                                                            public void onNext(BeanStatusInfo beanStatusInfo) {

                                                                                                                if (beanStatusInfo.getStatus() == 1) {

                                                                                                                    refresh();

                                                                                                                } else {
                                                                                                                    Toast.makeText(AddressSelectActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();

                                                                                                                }

                                                                                                            }
                                                                                                        }

                                                                                             );


                                                                                 }
                                                                             }

                                                                     )
                                                             .

                                                                     show();


                                                     return true;
                                                 }
                                             }

        );

    }

    private void initData() {
        mList = new ArrayList<>();
    }

    private void initView() {

        mSRL = (SwipeRefreshLayout) findViewById(R.id.activity_address_select_srl);
        mSRL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));

        btnBack = (LinearLayout) findViewById(R.id.activity_address_select_btn_back);
        btnAddAddress = (Button) findViewById(R.id.activity_address_select_btn_add);
        mListView = (ListView) findViewById(R.id.activity_address_select_lv);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_address_select_btn_back:
                // TODO: 2016/11/29 返回键
                Log.e("btnBack", "onClick: ");
                onBackPressed();
                break;

            case R.id.activity_address_select_btn_add:
                // TODO: 2016/11/29 添加地址
                break;
        }
    }
}
